import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/services.dart';

class FlutterBluetoothPlugin {
  factory FlutterBluetoothPlugin() => _getInstance();
  static FlutterBluetoothPlugin _instance;

  FlutterBluetoothPlugin._internal() {
    // 初始化
  }

  static FlutterBluetoothPlugin _getInstance() {
    if (_instance == null) {
      _instance = new FlutterBluetoothPlugin._internal();
    }
    return _instance;
  }

  static final String NAME_SPACE = "flutter_bluetooth_plugin";
  static final MethodChannel channel = MethodChannel(NAME_SPACE);
  static final EventChannel eventChannel = EventChannel("${NAME_SPACE}/state");

  ///关闭蓝牙
  Future<String> turnOff() async {
    return await channel.invokeMethod("turnOff");
  }

  ///打开蓝牙
  Future<String> turnOn() async {
    return await channel.invokeMethod("turnOn");
  }

  Future<String> startScan() async {
    return await channel.invokeMethod("startScan");
  }

  Future<String> stopScan() async {
    return await channel.invokeMethod("stopScan");
  }

  Future<String> connect(String address) async {
    Map map = new Map();
    map["connectDeviceAddress"] = address;
    return await channel.invokeMethod("connectDevice", map);
  }

  Future<String> sendMsg(String msg)async{
    Map map = new Map();
    map["msg"] = msg;
    return await channel.invokeMethod("sendMsg",map);
  }
  static Future startHandler(MethodCall call) {
    String name = call.method;
    var data = call.arguments;
    switch (name) {
      case "deviceResultListener":
        var msg = data["data"];
        if (_blueResultCallback != null) {
          _blueResultCallback(msg);
        }
        break;
      case "blueState":
        var state=data["state"];
        if(_blueStateCallback!=null){
          _blueStateCallback(state);
        }
        break;
      case "messageListener":
        if(_blueMessageCallback!=null){
          var message=data["message"];
          _blueMessageCallback(message);
        }
        break;
      default:

        break;
    }
  }

  static startListener() {
    channel.setMethodCallHandler(startHandler);
  }


  static BlueResultCallback _blueResultCallback;

  static void setBlueBlueResultCallback(BlueResultCallback callback) {
    _blueResultCallback = callback;
  }

  static BlueMessageCallback _blueMessageCallback;

  static void setBlueMessageCallback(BlueMessageCallback callback) {
    _blueMessageCallback = callback;
  }

  static BlueStateCallback _blueStateCallback;

  static void setBlueStateCallback(BlueStateCallback callback) {
    _blueStateCallback = callback;
  }
}

typedef void BlueResultCallback(String deviceMessage);//蓝牙地址扫描结果
typedef void BlueMessageCallback(String msg);//服务端发来的消息
typedef void BlueStateCallback(int state);//状态监听
